package com.xnx3.banmahuishou.core.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.xnx3.BaseVO;
import com.xnx3.banmahuishou.core.entity.GoodsPrice;
import com.xnx3.banmahuishou.core.service.PriceService;
import com.xnx3.banmahuishou.core.vo.PriceVO;
import com.xnx3.j2ee.service.SqlCacheService;
import com.xnx3.j2ee.service.SqlService;
import com.xnx3.wangmarket.shop.core.entity.Goods;
import com.xnx3.wangmarket.shop.core.entity.GoodsType;

@Service
public class PriceServiceImpl implements PriceService {
	@Resource
	private SqlCacheService sqlCacheService;
	@Resource
	private SqlService sqlService;
	
	public static final Integer CACHE_TIME = 30;	//缓存时间30秒
	
	public SqlCacheService getSqlCacheService() {
		return sqlCacheService;
	}
	public void setSqlCacheService(SqlCacheService sqlCacheService) {
		this.sqlCacheService = sqlCacheService;
	}
	
	@Override
	public PriceVO getPriceByGoodsTypeId(int goodsTypeId,int dlsUserid) {
		PriceVO vo = new PriceVO();
		
		//查大分类
		GoodsType goodsType = sqlCacheService.findById(GoodsType.class, goodsTypeId, CACHE_TIME);
		if(goodsType == null) {
			vo.setBaseVO(BaseVO.FAILURE, "大分类不存在");
			return vo;
		}
		
		//查大分类下的商品列表
		List<Goods> goodsList = sqlCacheService.findByProperty(Goods.class, "typeid",  goodsType.getId(), CACHE_TIME);
		if(goodsList.size() == 0) {
			vo.setBaseVO(BaseVO.FAILURE, "大分类下没有商品");
			return vo;
		}
	    if (dlsUserid > 1) {
			// 查询代理商商品金额表,看看是否有数据
			String sqlString = "SELECT * FROM laji_goods_price WHERE agencyid = " + dlsUserid;
			List<GoodsPrice> goodsPrices = sqlService.findBySqlQuery(sqlString, GoodsPrice.class);
			if (goodsPrices != null && goodsPrices.size() > 0) {
				for (Goods goods : goodsList) {
					for (GoodsPrice goodsPrice : goodsPrices) {
						if (goods.getId() - goodsPrice.getGoodsid() == 0) {
							// 该商品被代理商修改了价格,给附上价格
							goods.setMinMoney(goodsPrice.getMinMoney());
							goods.setMaxMoney(goodsPrice.getMaxMoney());
						}
					}
				}
			}
		}
		int sumMinPrice = 0;	//所有商品的最低价的和
		int sumMaxPrice = 0;	//所有商品的最高价的和
		for (int i = 0; i < goodsList.size(); i++) {
			Goods goods = goodsList.get(i);
			sumMinPrice = sumMinPrice + goods.getMinMoney();
			sumMaxPrice = sumMaxPrice + goods.getMaxMoney();
		}
		//计算出最低价跟最高价的平均价格
		int averageMinPrice = sumMinPrice / goodsList.size();
		int averageMaxPrice = sumMaxPrice / goodsList.size();
		//计算出用以计算的具体预估价格，那就直接最小价格跟最大价格的平均数
		int price = (averageMinPrice + averageMaxPrice) / 2;
		
		vo.setMinPrice(averageMinPrice);
		vo.setMaxPrice(averageMaxPrice);
		vo.setPrice(price);
		return vo;
	}

}
